<template>
  <div class="mod-config">
    <el-card class="box-card search-input" shadow="never">
      <el-form  label-width="120px"  size="mini" :model="dataForm" @keyup.enter.native="findPage()">
        <el-row>
          <el-col :span="6">
            <el-form-item label="标题：">
              <el-input v-model="dataForm.title" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建日期：">
              <el-date-picker
                @change="createTimeChange"
                style="width: 100%"
                v-model="createTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生效日期：">
              <el-date-picker
                @change="timesChange"
                style="width: 100%"
                v-model="times"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态：">
              <cy-select :list="status" v-model="dataForm.status"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button type="primary" @click="$refs.CyTable.query(dataForm)">查询</el-button>
              <el-button @click="reset('dataForm')">重置</el-button>
              <el-button type="primary" @click="showEdit">新增首页</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </el-card>
    <LiveHomeInfoTable
      url="/api/v1/liveHomeInfo/list"
      :max-height="600"
      :highlightCurrentRow="true"
      :operationWidth="350"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showEditOperation="true"
      :showDeleteOperation="true"
      @handleDelete="handleDelete"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleCustom="handleCustom"
      @effectDataFormSubmit="effectDataFormSubmit"
      @issueDataFormSubmit="issueDataFormSubmit"
      ref="CyTable"
    >
    </LiveHomeInfoTable>
    <el-dialog
      width="50%"
      :title="operationText"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      @close="editCancel">
      <el-row v-loading="addLoading">
        <el-form  label-width="120px" ref="editDataForm" size="mini" :rules="rules" :model="editDataForm">
          <el-col :span="24">
            <el-form-item label="标题：" prop="title">
              <el-input :disabled="isDisabledEdit"  maxlength="20" placeholder="最多可编辑20个字" v-model="editDataForm.title" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="副标题：" prop="subTitle">
              <el-input :disabled="isDisabledEdit" maxlength="20" placeholder="最多可编辑20个字" v-model="editDataForm.subTitle" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面：" prop="pic">
              <cy-file-upload
                :disabled="isDisabledEdit"
                :customStyle="fileStyle"
                v-model="editDataForm.pic"
                @onSuccess="fileUploadSuccess"
                :before-upload="beforeAvatarUpload"
              ></cy-file-upload>
              <div>封面图片请上传尺寸为200*200的图片</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="生效时间：" prop="status">
              <el-radio-group :disabled="isDisabledEdit"  @change="editStatusChange" v-model="editDataForm.status">
                <el-radio :label="21">立即生效</el-radio>
                <el-radio :label="20">定时生效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="editDataForm.status === 20">
            <el-form-item label="生效时间：" prop="times">
              <el-date-picker
                :disabled="isDisabledEdit"
                v-model="editDataForm.times"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                :picker-options="pickerOptions"
                placeholder="选择生效时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10" offset="8">
            <el-button size="mini" v-if="!isDisabledEdit"  @click="dataFormSubmit('editDataForm',20)">发布</el-button>
            <el-button size="mini" v-if="!isDisabledEdit"  type="primary" @click="dataFormSubmit('editDataForm',0)">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import CyTable from "./component/CyTable";
  import CySelect from "./component/CySelect";
  import CyFileUpload from "./component/CyFileUpload";
  import LiveHomeInfoTable from "./component/LiveHomeInfoTable";
  export default {
    components: {
      CyTable,
      CySelect,
      CyFileUpload,
      LiveHomeInfoTable
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        loading: false,
        addLoading: false,
        moreBtnDisable: true,
        status: [{
          label:'全部'
        },{
          value: 20,
          label: '待生效'
        }, {
          value: 21,
          label: '已生效'
        }, {
          value: 22,
          label: '已失效'
        }],
        isDisabledEdit:false,
        operationText: '新增首页',
        createTime: [],
        times: [],
        dataForm: {},
        editDataForm: {
          status: 21,
          type: 0,
          pic: ''
        },
        imageAddBtn:{
          width: '180px',
          height: '120px',
          marginBottom: '10px'
        },
        columns: [],
        filterColumns: [],
        bannerList:[],
        pageRequest: {pageNum: 1, pageSize: 10},
        totalSize: 0,
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        countNumForm: {
          allShopNum: '',
          onlineNum: '',
          offlineNum: ''
        },
        fileStyle:{
          width: '200px',
          height: '200px',
          marginBottom: '10px'
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        exportConfirmFlag: false,
        dataListSelections: [],
        invoiceUpdateVisible: true,
        rules: {
          title: [
            { required: true, message: '请填写首页名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择跳转类型', trigger: 'change' }
          ],
          pic: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ],
          status: [
            { required: true, message: '生效方式必选', trigger: 'change' }
          ],
          times: [
            { required: true, message: '生效时间必选', trigger: 'change' },
            {
              validator:this.verifyAnchor,
              trigger: 'blur'
            }
          ]
        },
      }
    },
    mounted: function () {
      this.columns = [
        {prop: "id", label: "首页编号", minWidth: 120},
        {prop: "title", label: "标题", minWidth: 120},
        {prop: "subTitle", label: "副标题", minWidth: 180},
        {prop: "pic", label: "封面", minWidth: 120, showType:'image',imgSize:{width:100,height:100}},
        {prop: "createTime", label: "创建日期", minWidth: 180},
        {prop: "times", label: "生效日期", minWidth: 180},
        {prop: "status", label: "状态", minWidth: 120, formatter:this.statusVal}
      ];
      let temp = [];
      this.columns.forEach(function (key, val) {
        temp.push(key);
      });
      this.filterColumns = temp;
    },
    methods: {
      verifyAnchor(rule, value, callback){
        value =new Date(Date.parse(value.replace(/-/g, "/")));
        this.utils.request.liveRequest({
          url: '/api/v1/liveHomeInfo/getServiceTime',
          method: 'get',
        }).then(result => {
          let data = result.data;
          if (data.code == '0') {
            //防止点击此刻获取服务延迟导致不可用 + 1分钟
            if((value.getTime()+1000*60)<data.data){
              callback(new Error('生效时间不能小于当前时间'));
            }
            callback();
          }
        })
      },
      // 获取数据列表
      findPage() {
        this.$refs.CyTable.findPage(this.dataForm);
      },
      statusVal(row, column, cellValue, index){
        if(cellValue==0) {
          return "待编辑"
        }else if(cellValue==20) {
          return "待生效"
        } else if(cellValue==21) {
          return "已生效"
        }else if(cellValue==22) {
          return "已失效"
        }
        return "";
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.findPage()
      },
      //将查询结果导出
      exportConfirm() {
        this.exportConfirmFlag = true;
        this.getDetailList();
      },

      getDetailList() {
        if (this.exportConfirmFlag) {
          this.auditExport();
          // this.findPage();
        }
        this.dataListLoading = false
      },
      //重置
      reset(formName) {
        this.dataForm={};
        this.createTime=[];
        this.times=[];
        this.$refs.CyTable.resetForm(this.dataForm);
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.findPage()
      },
      // 多选
      /*selectionChangeHandle(val) {
          this.dataListSelections = val
          if (this.dataListSelections.length > 0) {
              this.moreBtnDisable = false
          } else {
              this.moreBtnDisable = true
          }
      },*/
      // 显示编辑界面
      handleEdit: function (params) {

        if(params.type=='detail'){
          this.operationText= '查看首页';
          this.isDisabledEdit= true;
        }else{
          this.operationText= '编辑首页';
          this.isDisabledEdit= false;
        }
        this.dialogVisible = true;
        this.operation = false;
        this.editDataForm = Object.assign({}, params.row);
        this.$nextTick(() => {
          if (this.$refs['editDataForm'] !== undefined) {
            this.$refs['editDataForm'].clearValidate();
          }
        });
      },
      showEdit(){
        this.operationText= '新增首页';
        this.editDataForm= {
          'status': 21,
          'type': 0,
          'pic': ''
        },
          this.isDisabledEdit= false;
        this.dialogVisible = true;
      },
      // 删除
      handleDelete: function (params) {
        let ids = params.params;
        let delDataForm = [];
        ids.forEach(val=>{
          delDataForm.push(val)
        })
        if(delDataForm.length>0){
          let this_ = this;
          this.utils.request.liveRequest({
            url: '/api/v1/liveHomeInfo/batchDelete',
            method: 'post',
            params: delDataForm
          }).then(result => {
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
          })
        } else {
          this.$message({message: "请选择需要删除的数据", type: "info"});
        }

      },
      // 显示自定义界面
      handleCustom: function (params) {
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params.row);
        this.$nextTick(() => {
          if (this.$refs['dataForm'] !== undefined) {
            this.$refs['dataForm'].clearValidate();
          }
        });
      },
      // 创建日期改变
      createTimeChange: function (val) {
        if (val) {
          this.dataForm.createTimeStart = val[0]
          this.dataForm.createTimeEnd = val[1]
        } else {
          this.dataForm.createTimeStart = ''
          this.dataForm.createTimeEnd = ''
        }
      },
      // 生效日期改变
      timesChange: function (val) {
        if (val) {
          this.dataForm.timesStart = val[0]
          this.dataForm.timesEnd = val[1]
        } else {
          this.dataForm.timesStart = ''
          this.dataForm.timesEnd = ''
        }
      },
      editTimesChange(val){
        if(this.editDataForm.times===0){
          this.editDataForm.times = ''
        }
      },
      editStatusChange(val){
        // if(this.editDataForm.status===0){
        //     this.editDataForm.status = ''
        // }
      },
      // 编辑取消
      editCancel(){
        this.dialogVisible = false
        this.editDataForm = {
          type: 0,
          pic: ''
        }
      },
      // 新增提交
      dataFormSubmit(formName,status){
        formName.status=status;
        let this_ = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addLoading=true;
            this.utils.request.liveRequest({
              url: '/api/v1/liveHomeInfo/save',
              method: 'Post',
              params: this.editDataForm
            }).then(result => {
              this_.editCancel();
              let data = result.data;
              if (data.code === '0') {
                this_.$refs.CyTable.findPage(this_.dataForm)
                this_.$forceUpdate();
                this.$message({message: "操作成功", type: "success"});
              }else{
                this.$message({message: "操作失败", type: "error"});
              }
              this.addLoading=false;
            })
          } else {
            return false;
          }
        });
      },

      effectDataFormSubmit(row){
        let id=row.row.id;
        console.log(id);
        let this_ = this;
        let param={"id":id};
        this.$confirm("确认生效该条信息吗", "提示", {}).then(() => {
          this.utils.request.liveRequest({
            url: '/api/v1/liveHomeInfo/effect',
            method: 'Post',
            params: param
          }).then(result => {
            this_.editCancel();
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
          })
        })
      },

      //发布
      issueDataFormSubmit(row){

        let id=row.row.id;
        console.log(id);
        let this_ = this;
        let param={"id":id};
        this.$confirm("确认发布该条信息吗", "提示", {}).then(() => {
          this.utils.request.liveRequest({
            url: '/api/v1/liveHomeInfo/issue',
            method: 'Post',
            params: param
          }).then(result => {
            this_.editCancel();
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
          })
        })
      },
      // 测试代码
      fileUploadSuccess(res, file) {
        this.editDataForm.pic = res.data;
      },
      beforeAvatarUpload(file) {
        // 限制图片大小
        const isSize = new Promise((resolve,reject)=> {
          let width = 200;
          let height = 200;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            let valid = img.width == width && img.height == height
            valid ? resolve() : reject();
          }
        })
          .then(()=>{
            return file;
          },()=>{
            this.$message.error('上传图片像素格式为200*200!');
            return Promise.reject();
          })
        return isSize;
      }
    }
  }
</script>
<style scoped lang="scss">

</style>
